import store from "../store";
import router from "../router";
router.beforeEach(async (to, from, next) => {
  if (to.fullPath != "/") {
    var routers = store.state.routers;
    if (
      !store.state.userName ||
      (routers.length <= 0 && store.state.userName == "admin")
    ) {
      try {
        var username = await store.dispatch("getUserName");
        routers = store.state.routers;
        if (routers.length > 0) {
          routers.forEach((item) => {
            router.addRoute("layout", item);
          });
        }
        if (username) {
          next({ ...to });
        } else {
          next({ path: "/" });
        }
      } catch (error) {
        console.log(error);
        next({ path: "/" });
      }
    } else {
      next();
    }
  } else {
    next();
  }
});
